import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(
          useMaterial3: false,
          primarySwatch: Colors.blue,
        ),
        home: const MyHome()
    );
  }
}

class MyHome extends StatefulWidget {
  const MyHome({super.key});

  @override
  State<MyHome> createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {

  //必须声明泛型
  final GlobalKey<AnimatedListState> _globalKey = GlobalKey<AnimatedListState>();

  List<String> list = ["第一条","第二条"];

  @override
  void initState() {
    super.initState();
  }


  Widget _buildItem(index){
    return ListTile(
      title: Text(list[index]),
      trailing: IconButton(
        icon: const Icon(Icons.delete),
        onPressed: (){
          _deleteItem(index);
        },
      ),
    );
  }

  void _deleteItem(index){
    _globalKey.currentState!.removeItem(index, (context, animation) {
          var removeItem = _buildItem(index);
          list.removeAt(index);
          return ScaleTransition(
            // opacity: animation,
            scale: animation,
            child: removeItem,  //要删除的元素
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Flutter App"),
      ),
      body: AnimatedList(
        key: _globalKey,
        initialItemCount: list.length,
        itemBuilder: (context,index,animation){
          return FadeTransition(
            opacity: animation,
            child: _buildItem(index),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // AnimatedList无法通过setState()来新增数据
          //只能通过AnimatedListState的insertItem()和removeItem()来操作列表
         /* setState(() {
            list.add("我是新增的数据");
          });*/

          list.add("我是新增的数据");
          _globalKey.currentState!.insertItem(list.length-1 <=0 ? 0:list.length-1 );
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}

